local curl = require "lcurl.safe"
local json = require "cjson.safe"
script_info = {
	["title"] = "云解析通道",
	["version"] = "0.0.6",
	["color"] = "#57C43C",
	["description"] = "Admire's 共享号\n1.只能单任务下载\n2.不能多个人使用（几个人）\n3.更新时间2021-4-7\n4.错误-1表示不能读取秒传地址\n5.403说明用的人太多了，请稍等再尝试\n5.密钥在Telegram",
}

function request(url,header)
	local r = ""
	local c = curl.easy{
		url = url,
		httpheader = header,
		ssl_verifyhost = 0,
		ssl_verifypeer = 0,
		followlocation = 1,
		timeout = 30,
		proxy = pd.getProxy(),
		writefunction = function(buffer)
			r = r .. buffer
			return #buffer
		end,
	}
	local _, e = c:perform()
	c:close()
	return r
end

function onInitTask(task, user, file)
	for k,v in pairs(file) do
		pd.logInfo(k)
		pd.logInfo(v)
	end
	
	local dlinklink = file.dlink
    --TASK_TYPE_BAIDU
    if task:getType() ~= TASK_TYPE_SHARE_BAIDU then
		--task:setError(-1,"必须分享下载")
		local header = {}
		table.insert(header,"User-Agent: netdisk")
		table.insert(header,"Cookie: BDUSS="..user:getBDUSS())
		local fsid = string.format("%d",file.id)
		local url = "https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&dlink=1&fsids=%5b"..fsid.."%5d"
		local result = request(url,header)
		local resultjson = json.decode(result)
		if resultjson == nil then
		task:setError(-1,"网络错误")
		pd.logError('网络超时')
		return true
		end
		local dlink = resultjson.list[1].dlink
		dlinklink = dlink
	end
	
	
	--local url = "http://127.0.0.1:8989/api/yjx?dlink="..dlinklink
	--dlink=string.sub(dlink, 0,string.len(dlink)-2)
	local url = "http://146.56.234.175:81/yjx11.php?dlink="..pd.base64Encode(dlinklink).."&key="..pd.getConfig("Baidu","accelerateURL")--@fixpds
	pd.logInfo(url)
	local data = ""
	local header = { "User-Agent: netdisk;P2SP;2.2.60.26" }
	
	local c = curl.easy{
		url = url,
		followlocation = 1,
		httpheader = header,
		timeout = 100,
		proxy = pd.getProxy(),
		writefunction = function(buffer)
			data = data .. buffer
			return #buffer
		end,
	}
    local _, e = c:perform()
    c:close()
    if e then
        task:setError(-1,"链接至云服务器超时")
		return true
    end
	pd.logInfo(data)
	local j = json.decode(data)
	if j == nil then
		
		task:setError(-1,"请求错误，链接云解析失败")
		return true
	end
	
	if string.find(data, "issuecdn") ~= nil then 
		task:setError(-1,"违禁文件，已被禁止下载")
		return true
	end

	local j = json.decode(data)
	--local j = json.decode(data)


	--local message = {}
	--for i, w in ipairs(j.server) do
	--	table.insert(message, j.server[i])
	--end
    --local num = pd.choice(message, 1, "选择下载接口")
    --local downloadURL = "https://"..j.server[num]..j.path
	if j.errno ~= "0" then 
		task:setError(-1,j.msg)
		return true
	end
	local downloadURL = j.url
	local ua=j.ua
	pd.logInfo("下载地址："..downloadURL)
	task:setUris(downloadURL)
	task:setOptions("user-agent", ua)
    --task:setOptions("header", "Cookie: "..user:getCookie())
	task:setOptions("piece-length", "1M")
	task:setOptions("max-connection-per-server", "1")
	task:setOptions("split", "1")
	task:setOptions("piece-length", "1M")
    return true
end